package com.rp.system.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.raptor.pagination.Page2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.jfinal.plugin.activerecord.Db;
import com.rp.common.utils.JsonUtil;
import com.rp.common.utils.RpUtil;
import com.rp.common.vo.PageData;
import com.rp.controller.RpController;
import com.rp.system.po.Menu;
import com.rp.system.po.MenuItem;
import com.rp.system.po.User;
import com.rp.system.service.MenuService;

@Controller
@RequestMapping("/rp/system/baseData/menuMng/")
public class MenuController extends RpController {
	
	@Autowired
	private MenuService menuService;
	
	@RequestMapping("showMenuGrid")
	public ModelAndView showMenuGrid(){
		model.put("webpageTitle", "菜单管理");
		return forward("/rp/system/baseData/menuMng/menuGrid.jsp");
	}
	
	@RequestMapping("showMenuItemMng")
	public ModelAndView showMenuItemMng(){
		model.put("webpageTitle", "菜单项管理");
		return forward("/rp/system/baseData/menuMng/menuItemMng.jsp");
	}
	
	/**
	 * 获取主界面侧边栏中显示的菜单
	 * @param show
	 * @return
	 */
	@ResponseBody
	@RequestMapping("getAllMenus")
	public List<Menu> getAllMenus(String show){
		return menuService.getMenuDao().getAllMenus(show);
	}
	
	@ResponseBody
	@RequestMapping("getMenus")
	public PageData getMenus(){
		Page2 page = menuService.getMenuDao().getMenusByPage(pageParam);
		return new PageData(page);
	}
	
	/**
	 * （新）RP平台后台主界面左侧边栏获取需要显示的菜单项的方法，获取的菜单项与角色关联
	 * @param menuName 菜单名称
	 * @return
	 */
	@ResponseBody
	@RequestMapping("showMenuItems2")
	public List<Map<String, Object>> showMenuItems2(String menuName){
		List<Map<String, Object>> menuItems = new ArrayList<Map<String, Object>>();
		String inParam = "";
		String menuId = Db.use("rpDb").queryStr("select id from RP_SYSTEM_MENUS where name = ?", menuName);
		User currentUser = User.getCurrentUser();
		String roleId = currentUser.getRoleId();
		String menuItemIds = Db.use("rpDb").queryStr("select menuItemIds from RP_SYSTEM_ROLE_MENUS where roleId = ? and menuId = ?", roleId, menuId);
		if(!RpUtil.isNullOrEmpty(menuItemIds)){
			String[] menuItemIdArr = menuItemIds.split(",");
			for (int i=0; i<menuItemIdArr.length; i++) {
				if(i == (menuItemIdArr.length-1)){
					inParam = inParam + "'" + menuItemIdArr[i] + "'";
				}else{
					inParam = inParam + "'" + menuItemIdArr[i] + "',";
				}
			}
			menuItems = RpUtil.jfinalListToList(
					Db.use("rpDb").find("select * from rp_system_menuitems mi where mi.id in ("+inParam+") order by sort asc"));
		}
		
		return menuItems;
	}
	
	/**
	 * 获取所有菜单项,包括未激活的,此方法用在菜单项管理界面
	 * @param menuId 菜单ID
	 * @return
	 */
	@ResponseBody
	@RequestMapping("getMenuItems")
	public List<MenuItem> getMenuItems(String menuId){
		List<MenuItem> mis = menuService.getMenuItemDao().getAllMenuItemsByMenuId(menuId);
		return mis;
	}
	
	/**
	 * 获取所有激活的菜单项
	 * @param menuId 菜单ID
	 * @return
	 */
	@ResponseBody
	@RequestMapping("getMenuItemsByEnabled")
	public List<Map<String, Object>> getMenuItemsByEnabled(String menuId){
		return RpUtil.jfinalListToList(Db.use("rpDb")
				.find("select * from RP_SYSTEM_MENUITEMS where menuId = ? and enabled2 = '1' order by sort asc", menuId));
	}
	
	/**
	 * 检查菜单名称是否已存在
	 * @param menuName
	 * @return
	 */
	@ResponseBody
	@RequestMapping("checkMenuNameExist")
	public String checkMenuNameExist(String menuName){
		if(menuService.checkMenuNameExist(menuName)){
			return ERROR;
		}
		return SUCCESS;
	}
	
	@ResponseBody
	@RequestMapping("saveMenus")
	public String saveMenus(String data){
		try {
			List<Menu> menus = JsonUtil.jsonToList(data, "com.rp.system.po.Menu");
			for (Menu menu : menus) {
				if(menu.getId() == null){
					menuService.saveMenu(menu);
				}else{
					menuService.updateMenu(menu);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return e.getMessage();
		}
		return SUCCESS;
	}
	
	@ResponseBody
	@RequestMapping("deleteMenus")
	public String deleteMenus(String data){
		try {
			List<Menu> ms = JsonUtil.jsonToList(data, "com.rp.system.po.Menu");
			for (Menu menu : ms) {
				menuService.deleteMenu(menu.getId());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return SUCCESS;
	}
	
	@ResponseBody
	@RequestMapping("saveMenuItems")
	public String saveMenuItems(String data, String menuId, String menuName){
		
		try {
			//下面这段代码用于树的保存更新
			/*ArrayList list = JsonUtil.toList((ArrayList)JsonUtil.decode(data), "-1", "children", "id", "pid");
			String json = JsonUtil.getMapper().writeValueAsString(list);
			List<MenuItem> mis = JsonUtil.getMapper().readValue(json, JsonUtil.getCollectionType(ArrayList.class, MenuItem.class));
			for (MenuItem menuItem : mis) {
				menuService.updateMenuItem(menuItem, menuId);
			}*/
			List<MenuItem> mis = JsonUtil.jsonToList(data, "com.rp.system.po.MenuItem");
			for (MenuItem menuItem : mis) {
				if(menuItem.getId() == null){
					menuService.saveMenuItem(menuItem, menuId, menuName);
				}else{
					menuService.updateMenuItem(menuItem);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	@ResponseBody
	@RequestMapping("deleteMenuItem")
	public String deleteMenuItem(String id){
		menuService.deleteMenuItem(id);
		return SUCCESS;
	}
	
	@ResponseBody
	@RequestMapping("deleteMenuItems")
	public String deleteMenuItems(String data){
		try {
			List<MenuItem> mis = JsonUtil.jsonToList(data, "com.rp.system.po.MenuItem");
			for (MenuItem menuItem : mis) {
				menuService.deleteMenuItem(menuItem.getId());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return SUCCESS;
	}
	
	/**
	 * 移动菜单项
	 * @param dragMenuItemId 被移动项ID
	 * @param dropMenuItemId 目标投放项ID
	 * @return
	 */
	@ResponseBody
	@RequestMapping("moveMenuItem")
	public String moveMenuItem(String dragMenuItemId, String dropMenuItemId){
		try{
			MenuItem dragMi = menuService.getMenuItemDao().get(dragMenuItemId);
			MenuItem dropMi = menuService.getMenuItemDao().get(dropMenuItemId);
			String dragSort = dragMi.getSort();
			String dropSort = dropMi.getSort();
			//如果源节点与目标节点同属一个父节点下
			if(dragMi.getPid().equals(dropMi.getPid())){
				dragMi.setSort(dropSort);
				dropMi.setSort(dragSort);
				menuService.updateMenuItem(dragMi);
				menuService.updateMenuItem(dropMi);
			}else{
				if(dropMi.getPid().equals("-1") || dropMi.getPid().equals("NULL")){
					dragMi.setPid(dropMi.getId());
					dragMi.setSort(dropMi.getSort()+"-N");
					menuService.updateMenuItem(dragMi);
				}else{
					dragMi.setPid(dropMi.getPid());
					MenuItem parentMi = menuService.getMenuItemDao().get(dropMi.getPid());
					dragMi.setSort(parentMi.getSort()+"-N");
					menuService.updateMenuItem(dragMi);
				}
			}
			//dragMi.setPid(dropMenuItemId);
			//menuService.updateMenuItem(dragMi);
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
		return SUCCESS;
	}
	
	@RequestMapping("showEditMenuItemForm")
	public ModelAndView showEditMenuItemForm(String menuItemId){
		model.put("menuItem", menuService.getMenuItemDao().get(menuItemId));
		return forward("/rp/system/baseData/menuMng/editMenuItemForm.jsp");
	}
	
	@ResponseBody
	@RequestMapping("importMenu")
	public String importMenu(String json){
		try {
			List<Menu> menus = JsonUtil.getMapper().readValue(json, JsonUtil.getCollectionType(ArrayList.class, Menu.class));
			for (Menu menu : menus) {
				if(menuService.checkMenuNameExist(menu.getName())){
					Menu dbMenu = menuService.getMenuDao().getMenuByName(menu.getName());
					dbMenu.setName(menu.getName());
					dbMenu.setTitle(menu.getTitle());
					dbMenu.setUrl(menu.getUrl());
					dbMenu.setIconCls(menu.getIconCls());
					menuService.updateMenu(dbMenu);
				}else{
					menuService.saveMenu(menu);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
		return SUCCESS;
	}
	
	@ResponseBody
	@RequestMapping("importMenuItem")
	public String importMenuItem(String json){
		try {
			List<MenuItem> menuItems = JsonUtil.getMapper().readValue(json, JsonUtil.getCollectionType(ArrayList.class, MenuItem.class));
			for (MenuItem mi : menuItems) {
				if(menuService.checkMenuItemTextExist(mi.getText())){
					MenuItem dbMenuItem = menuService.getMenuItemDao().getMenuItemByText(mi.getText());
					dbMenuItem.setUrl(mi.getUrl());
					dbMenuItem.setIconCls(mi.getIconCls());
					//dbMenuItem.setPid(mi.getPid());
					//dbMenuItem.setMenuId(mi.getMenuId());
					//dbMenuItem.setMenuName(mi.getMenuName());
					dbMenuItem.setSort(mi.getSort());
					dbMenuItem.setVerifyClose(mi.getVerifyClose());
					
					menuService.updateMenuItem(dbMenuItem);
				}else{
					menuService.saveMenuItem(mi, mi.getMenuId(), mi.getMenuName());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
		return SUCCESS;
	}
	
}
